'use strict';

import {getFileDir} from "../utils";

const RSVP = require('rsvp');
const app = require('../app');

const postJSON = require('./ajax/post_json');
import store from "@/store"
import get from "./ajax/get";
import loadAlgorithm from "./load_algorithm"
import request from "../../utils/request";
import Toast from "../dom/toast";

const {
  each
} = $;

const {
  setPath
} = require('./helpers');

const cachedContentExists = (cachedFile) => {
  return cachedFile &&
    cachedFile.data !== undefined &&
    cachedFile.code !== undefined;
};

const loadDataAndCode = (dir) => {
  return RSVP.hash({
    data: get(`${dir}data.js`),
    code: get(`${dir}code.js`),
    template: get(`${dir}template.txt`),
  });
};

const isTemplate = (dir) => {
  dir = dir.replace(/[\/#?]+$/, '');
  const lastPart = dir.split('/').pop().toLowerCase();
  let pattern1 = "template";
  let pattern2 = "模板";
  if(lastPart.indexOf(pattern1) !== -1 || lastPart.indexOf(pattern2) !== -1) {
    return true;
  }
  return false;
}

module.exports = (category, categoryName, name, algorithmName) => {
  const fileList = [];
  const allFileNames = Array.from(document.querySelectorAll(".files_bar > .wrapper > button"))
    .map(btn => btn.dataset.file)
    .filter(name => name !== undefined);
  console.log(category)
  console.log(categoryName)
  console.log(algorithmName)

  const tasks = allFileNames.map((file, index) => {
    let dir = getFileDir('scratch', '', file);
    const cachedFile = app.getCachedFile(dir);

    if (cachedContentExists(cachedFile)) {
      const { data, code, template, explanation } = cachedFile;
      if (isTemplate(dir)) {
        fileList.push({
          name: file,
          fileOrder: index,
          file: {
            data: '',
            code: '',
            template,
            desc: explanation,
          }
        });
      } else {
        fileList.push({
          name: file,
          fileOrder: index,
          file: {
            data,
            code,
            template: '',
            desc: explanation,
          }
        });
      }
      return Promise.resolve();
    } else {
      return loadAlgorithm('scratch', '').then((explanations) => {
        const explanation = explanations.files[file];
        return loadDataAndCode(dir).then((content) => {
          const { data, code, template } = content;
          if (isTemplate(dir)) {
            fileList.push({
              name: file,
              fileOrder: index,
              file: {
                data: '',
                code: '',
                template,
                desc: explanation,
              }
            });
          } else {
            fileList.push({
              name: file,
              fileOrder: index,
              file: {
                data,
                code,
                template: '',
                desc: explanation,
              }
            });
          }
        });
      });
    }
  });

  Promise.all(tasks).then(() => {
    const data = {
      desc: store.getters.markdown,
      files: fileList,
      'category': category,
      'categoryName': categoryName,
      'name': name,
      'algorithmName': algorithmName,
    };
    console.log(data);
    request({
      url: '/algorithm/scratch_paper/upload',
      method: 'post',
      data: data
    }).then(res => {
      if (res.code == 200) {
        Toast.showInfoToast('上传成功，待审核');
      } else {
        Toast.showErrorToast('系统错误，上传失败');
      }
    });
  });
};
